﻿<%@ WebHandler Language="C#" Class="BpmProblemRoleUsersMaint" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using System.Collections;
using ReportBusiness;

/*
 * Description:问题快反角色维护
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * create Date:2022.05.26
 */

public class BpmProblemRoleUsersMaint : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "addRole":
                        r = addRole(jObject);//新增角色
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "changeStatus":
                        r = changeStatus(jObject);//更新启用状态
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getUserList":
                        r = getUserList(jObject);//查询BPM用户列表
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "addRoleUsers":
                        r = addRoleUsers(jObject);//添加角色用户
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getRoleUsers":
                        r = getRoleUsers(jObject);//查询角色已维护用户
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "removeRoleUsers":
                        r = removeRoleUsers(jObject);//移除角色用户列表
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //新增角色
    Result addRole(JObject jObject)
    {
        Result r = new Result();
        string sql = string.Format("SELECT * FROM bpm_problem_role t WHERE t.rolename = '{0}'", jObject["rolename"].ToString());

        if (dal.GetDataTable(sql).Rows.Count != 0)
        {
            r.data = null;
            r.total = Convert.ToInt32(0);
            r.meta = new Result.Meta(200, "该角色已存在，不能重复添加");
            return r;
        }

        sql = @"
INSERT INTO bpm_problem_role t (roleid,rolename,createuser,createdate,status) VALUES('{0}','{1}','{2}',sysdate,1)
";
        sql = string.Format(sql,
            Guid.NewGuid().ToString(),//唯一id
            jObject["rolename"].ToString(),//角色名
            jObject["employeeid"].ToString()//创建人
            );

        int count = dal.ExecuteSql(sql);

        if (count > 0)
        {
            r.data = null;
            r.total = Convert.ToInt32(1);
            r.meta = new Result.Meta(200, "添加成功");
        }
        else
        {
            r.data = null;
            r.total = Convert.ToInt32(0);
            r.meta = new Result.Meta(500, "添加失败");
        }
        return r;
    }

    //查询
    Result getData(JObject jObject)
    {
        Result r = new Result();
        string sql = @"
SELECT t.roleid,t.rolename,e.fullname createuser,t.createdate,t.status,e2.fullname updateuser,t.updatedate
FROM bpm_problem_role t 
LEFT JOIN employee e ON e.employeeid = t.createuser
LEFT JOIN employee e2 ON e2.employeeid = t.updateuser
WHERE 1=1 
";
        if (jObject["rolename"] != null && jObject["rolename"].ToString() != "")
        {
            sql += string.Format(" AND t.rolename LIKE '%{0}%'", jObject["rolename"].ToString());
        }

        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //切换状态
    Result changeStatus(JObject jObject)
    {
        Result r = new Result();
        string sql = @" UPDATE bpm_problem_role t SET t.status='{1}',t.updatedate = sysdate,t.updateuser='{2}' WHERE t.roleid='{0}' ";

        int status = 0;
        if (jObject["status"] != null)
        {
            status = jObject["status"].ToString() == "True" ? 1 : 0;
        }

        sql = string.Format(sql, jObject["roleid"].ToString(), status, jObject["employeeid"].ToString());

        int count = dal.ExecuteSql(sql);

        r.data = null;
        r.total = count;
        r.meta = new Result.Meta(200, "状态切换成功");
        return r;
    }

    //添加角色用户
    Result addRoleUsers(JObject jObject)
    {
        Result r = new Result();
        JArray arr = JArray.Parse(jObject["userList"].ToString());
        ArrayList sqlList = new ArrayList();
        foreach (var item in arr)
        {
            sqlList.Add(string.Format("INSERT INTO bpm_problem_role_users(roleid, username) VALUES('{0}', '{1}')", jObject["roleid"].ToString(), item.ToString()));
        }

        try
        {
            dal.ExecuteSqlTran(sqlList);
            r.data = null;
            r.total = Convert.ToInt32(arr.Count);
            r.meta = new Result.Meta(200, "添加成功");
            return r;
        }
        catch (Exception e)
        {
            r.data = null;
            r.total = Convert.ToInt32(arr.Count);
            r.meta = new Result.Meta(500, e.Message);
            return r;
        }
    }

    //查询角色已配置用户列表
    Result getRoleUsers(JObject jObject)
    {
        Result r = new Result();
        string sql = @" 
SELECT t.username userid,u.username
FROM bpm_problem_role_users t
LEFT JOIN awsprd.feedback_orguser@bpm195 u ON u.userid = t.username
WHERE t.roleid = '{0}'
";
        sql = string.Format(sql, jObject["roleid"].ToString());

        DataTable dt = dal.GetDataTable(sql);

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;

    }

    //移除角色用户列表
    Result removeRoleUsers(JObject jObject)
    {
        Result r = new Result();
        string sql = "";

        JArray arr = JArray.Parse(jObject["userList"].ToString());

        foreach (var item in arr)
        {
            sql = string.Format("DELETE bpm_problem_role_users t WHERE t.roleid = '{0}' AND t.username = '{1}'", jObject["roleid"].ToString(), item.ToString());
            int i = dal.ExecuteSql(sql);
        }
        r.data = null;
        r.total = Convert.ToInt32(arr.Count);
        r.meta = new Result.Meta(200, "移除成功");
        return r;
    }

    Result getUserList(JObject jObject)
    {
        Result r = new Result();
        string sql = @"
SELECT t.userid,t.username,CASE WHEN ru.roleid IS NOT NULL THEN 'true' ELSE 'false' END disabled
FROM bpm_orguser_table t
LEFT JOIN 
(
    SELECT ru.roleid,ru.username 
    FROM bpm_problem_role_users ru
";
        if (jObject["roleid"] != null && jObject["roleid"].ToString() != "")
        {
            sql += string.Format(" WHERE ru.roleid = '{0}'", jObject["roleid"].ToString());
        }
        sql += @"
) ru ON ru.username = t.userid
WHERE t.departmentid IN (
  SELECT bp.departmentid
  FROM bpm_orgdepartment_table bp
  START WITH ";
        if (jObject["departmentid"] != null && jObject["departmentid"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["departmentid"].ToString());
            if (arr.Count != 0)
            {
                sql += string.Format(" bp.departmentid = '{0}'", arr[arr.Count - 1].ToString());
            }
        }
        sql += @"
  CONNECT BY PRIOR bp.departmentid = bp.parentdepartmentid
) ";
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "ok");
        return r;
    }
}